package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 文章同步ES监听器
 */
@Component
public class SyncArticleListener {
    @Autowired
    private RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message){

        //1.校验参数
        if(StringUtils.isBlank(message)){
            return;
        }
        //2.转换数据
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

        //3.存储到ES中
        IndexRequest indexRequest = new IndexRequest("app_info_article");
        indexRequest.id(searchArticleVo.getId().toString()).source(message, XContentType.JSON);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println("同步ES成功..."+ searchArticleVo.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
